package manage

import (
	"fmt"
	"mime/multipart"
	"os"
	"path/filepath"
	"time"

	"github.com/gofiber/fiber/v2"
	logger "github.com/sirupsen/logrus"

	"publish-manage/internal/model"
	"publish-manage/internal/service"
	"publish-manage/pkg/config"
	"publish-manage/pkg/constant"
	"publish-manage/pkg/domain"
)

var PublishController = new(publishController)

type publishController struct{}

func init() {
	path := config.GetString("server.packagePath")
	if path != "" {
		os.MkdirAll(path, os.ModePerm)
	}
}

func (c publishController) publish(ctx *fiber.Ctx) error {
	form, err := ctx.MultipartForm()
	if err != nil {
		logger.Error(err)
		return ctx.JSON(&domain.CommonResponse{
			Code: constant.ResponseCodeErrorParamParse,
			Msg:  "解析参数失败",
		})
	}

	apIds := form.Value["appPackageId"]
	if len(apIds) == 0 {
		return ctx.JSON(&domain.CommonResponse{
			Code: constant.ResponseCodeErrorParamRequired,
			Msg:  "应用部署包ID必须提供",
		})
	}
	appPackageId := apIds[0]
	agentIds := form.Value["agentId"]

	appPackage, err := service.AppPackageService.Get(&model.AppPackage{Id: appPackageId})
	if err != nil {
		logger.Error(err)
		return ctx.JSON(&domain.CommonResponse{
			Code: constant.ResponseCodeErrorInternal,
			Msg:  "获取应用部署包信息失败",
		})
	}
	if appPackage == nil {
		return ctx.JSON(&domain.CommonResponse{
			Code: constant.ResponseCodeErrorResourceNotFound,
			Msg:  "应用部署包信息不能存在",
		})
	}
	app, err := service.ApplicationService.Get(&model.Application{Id: appPackage.AppId})
	if err != nil {
		logger.Error(err)
		return ctx.JSON(&domain.CommonResponse{
			Code: constant.ResponseCodeErrorInternal,
			Msg:  "获取应用信息失败",
		})
	}
	if app == nil {
		return ctx.JSON(&domain.CommonResponse{
			Code: constant.ResponseCodeErrorResourceNotFound,
			Msg:  "应用信息不能存在",
		})
	}

	var fh *multipart.FileHeader

OUT:
	for _, fd := range form.File {
		for i := 0; i < len(fd); i++ {
			fh = fd[i]
			break OUT
		}
	}

	if fh == nil {
		return ctx.JSON(&domain.CommonResponse{
			Code: constant.ResponseCodeErrorParamRequired,
			Msg:  "请提供上传文件",
		})
	}

	path := filepath.Join(config.GetString("server.packagePath"), app.Name, appPackage.Name, fmt.Sprintf("%s-%s", time.Now().Format("200601021504"), fh.Filename))

	if err = ctx.SaveFile(fh, path); err != nil {
		logger.Error(err)
		return ctx.JSON(&domain.CommonResponse{
			Code: constant.ResponseCodeErrorInternal,
			Msg:  "读取文件发生错误",
		})
	}

	if err = service.ManagePublishService.Publish(path, appPackage, agentIds...); err != nil {
		logger.Error(err)
		return ctx.JSON(&domain.CommonResponse{
			Code: -1,
			Msg:  "部署文件发生错误",
		})
	}
	return ctx.JSON(&domain.CommonResponse{})
}
